package com.example.minademo.server;


import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import android.util.Log;

import com.example.minademo.interfaces.IMsgCallback;

public class ServerHandler extends IoHandlerAdapter { 
	
	public static final String TAG = "ServerHandler";
	
	private IMsgCallback mCallback;
	
	public ServerHandler(IMsgCallback callback) {
		
		mCallback = callback;
	}
	
	@Override
	public void messageSent(IoSession session, Object message) throws Exception {

		super.messageSent(session, message);

		Log.d(TAG, "client send msg to sever:" + message.toString());
		if (null != mCallback) {

			mCallback.clientReceiveMsg("client send msg to sever:"
					+ message.toString());
		}
		System.out.println("send msg to server: " + message.toString());
	}

    @Override 
    public void messageReceived(IoSession session, Object message) 
            throws Exception { 
          
    	String expression = message.toString(); 
    	
    	Log.d(TAG, "receive client msg: " + expression); 
    	
    	if (null != mCallback) {
    		
    		mCallback.serverReceiveMsg(message.toString());
    	}
    	
//        if ("quit".equalsIgnoreCase(expression.trim())) { 
//            session.close(true); 
//            return; 
//        } 
        
        String result = "echo: " + expression;
        session.write(result + " isService");

    } 
     
    @Override 
    public void exceptionCaught(IoSession session, Throwable cause) 
            throws Exception { 
        System.out.println("cat exception" +cause); 
    } 
    
    
    @Override
	public void sessionCreated(IoSession session) throws Exception {

		super.sessionCreated(session);
		System.out.println("sessionCreated~");
		if (null != mCallback) {

			mCallback.clientReceiveMsg("sessionCreated~");
		}
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		super.sessionOpened(session);
		if (null != mCallback) {

			mCallback.clientReceiveMsg("sessionOpened~");
		}
		System.out.println("sessionOpened~");
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		super.sessionClosed(session);
		if (null != mCallback) {

			mCallback.clientReceiveMsg("sessionClosed~");
		}
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		// TODO Auto-generated method stub
		super.sessionIdle(session, status);
		if (null != mCallback) {

			mCallback.clientReceiveMsg("sessionIdle~");
		}
	}

 
} 
